package cn.harry.utils;

import cn.harry.constant.*;
import cn.harry.entity.ColumnEntity;
import cn.harry.entity.TableEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器   工具类
 * @author hushuaifei
 */
public class GenUtils {
    //zgnFixme 1.统一配置
    //static GxTempEnum TempEnum=new GxTempEnum();
    //static GxDataCenTempEnum TempEnum=new GxDataCenTempEnum();
    //static 网站TempEnum TempEnum=new 网站TempEnum();
    //static 游戏王TempEnum TempEnum=new 游戏王TempEnum();
    //static 游戏王2TempEnum TempEnum=new 游戏王2TempEnum();
    //static SseTempEnum TempEnum=new SseTempEnum();
    static 羽毛球TempEnum TempEnum=new 羽毛球TempEnum();

    /**
     * 生成代码
     */
    public static void generatorCode(Map<String, String> table,
                                     List<Map<String, String>> columns, ZipOutputStream zip) {
        //配置信息
        boolean hasBigDecimal = false;

        Configuration config = getConfig();
        //表信息
        TableEntity tableEntity = new TableEntity();
        tableEntity.setTableName(table.get("tableName" ));
        tableEntity.setComments(table.get("tableComment" ));
        //表名转换成Java类名
        String className = tableToJava(tableEntity.getTableName(), TempEnum.tablePrefix);
        tableEntity.setClassName(className);
        tableEntity.setClassname(StringUtils.uncapitalize(className));//首字母转小写

        //列信息
        List<ColumnEntity> columsList = new ArrayList<>();
        for(Map<String, String> column : columns){
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setColumnName(column.get("columnName" ));
            columnEntity.setDataType(column.get("dataType" ));
            columnEntity.setComments(column.get("columnComment" ));
            columnEntity.setExtra(column.get("extra" ));
            columnEntity.setIsNull(column.get("isNull" ));

            //列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setAttrName(attrName);
            columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getDataType(), "unknowType" );
            columnEntity.setAttrType(attrType);
            if (!hasBigDecimal && "BigDecimal".equals(attrType)) {
                hasBigDecimal = true;
            }
            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey" )) && tableEntity.getPk() == null) {
                tableEntity.setPk(columnEntity);
            }

            columsList.add(columnEntity);
        }
        tableEntity.setColumns(columsList);

        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        //region 1.序列化 2.默认主键
        map.put("jsonAll", TempEnum.jsonAll);

        if (tableEntity.getPk() == null&&TempEnum.isPK) {
            tableEntity.setPk(tableEntity.getColumns().get(0));
        }
        //endregion

        //region 表
        map.put("tableName", tableEntity.getTableName());
        map.put("comments", tableEntity.getComments());
        map.put("pk", tableEntity.getPk());
        map.put("className", tableEntity.getClassName());
        map.put("classname", tableEntity.getClassname());
        map.put("pathName", tableEntity.getClassname().toLowerCase());
        map.put("columns", tableEntity.getColumns());
        map.put("hasBigDecimal", hasBigDecimal);
        //endregion

        //region 包及基本信息
        map.put("mainPath", TempEnum.mainPath);//模板中没用
        map.put("package", TempEnum.packageName);
        map.put("moduleName", TempEnum.moduleName);

        map.put("author", TempEnum.author);
        map.put("email", TempEnum.email);
        map.put("copyright",TempEnum.copyright);
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        //endregion



        //region 设置velocity资源加载器
        VelocityEngine velocityEngine = new VelocityEngine();//junit 自用导入模板的方式
        Properties p = new Properties();
        p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, TempEnum.filePath);
        velocityEngine.init(p);
        VelocityContext context = new VelocityContext(map);
        //endregion

        //获取模板列表
        HashMap<String, String> templates = TempEnum.getTemplates();

        for (String templateMapKey : templates.keySet()) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl =velocityEngine.getTemplate(templateMapKey,"UTF-8");
            //Template tpl = Velocity.getTemplate(template, "UTF-8" );
            tpl.merge(context, sw);

            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry(Objects.requireNonNull(TempEnum.getFileName(templateMapKey, tableEntity.getClassName(), TempEnum.packageName, TempEnum.moduleName))));
                IOUtils.write(sw.toString(), zip, "UTF-8" );
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new RRException("渲染模板失败，表名：" + tableEntity.getTableName(), e);
            }
        }
    }

    /**
     * 列名转换成Java属性名
     * 按照空格和'_'大写,且删除'_'
     * @auther zgn
     * @date  2022/1/4 0004
     *
     * @param columnName
     *
     * @return columnName
     **/
    public static String columnToJava(String columnName) {
        //WordUtils_api https://blog.csdn.net/han12398766/article/details/104356444
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "" );
    }

    /**
     * 表名转换成Java类名
     * @auther zgn
     * @date  2022/1/4 0004
     *
     * @param tableName 表名
     * @param tablePrefix 去除前缀
     *
     * @return null
     **/
    public static String tableToJava(String tableName, String tablePrefix) {
        //去除tablePrefix前缀
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replaceFirst(tablePrefix, "" );
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            String relativelyPath = System.getProperty("user.dir");//获取当前项目的根目录
            return new PropertiesConfiguration(relativelyPath + "/src/main/resources/generator.properties" );
        } catch (Exception e) {
            throw new RRException("获取配置文件失败，", e);
        }
    }

}
